package com.wuwei.gulimall.product.service.impl;

import com.wuwei.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuwei.common.utils.PageUtils;
import com.wuwei.common.utils.Query;

import com.wuwei.gulimall.product.dao.CategoryDao;
import com.wuwei.gulimall.product.entity.CategoryEntity;
import com.wuwei.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1 查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        System.out.println(entities.size());
        //2 组装成父子树形结构
        //2.1找到所有的一级分类
        List<CategoryEntity> list = entities.stream()
                //找出最高级菜单，相当于找到根分类
                .filter(a -> a.getParentCid() == 0)
                //进行映射，找到根菜单的子菜单
                .map(menu->{menu.setChildren(getChildren(menu,entities)); return menu;})
                .sorted((menu1,menu2)->{
                    //按照sorted从小到大排序
                    return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?1:menu2.getSort());
                })
                .collect(Collectors.toList());
        return list;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.在这里删除之前要先检查当前删除的菜单是否被其他地方引用了
        //实际开发中大多使用逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] getParentPath(Long catelogId) {//找出attrGroupId的所有父分类
    List<Long> list = new ArrayList<>();
    list = findParent(catelogId,list);
    Collections.reverse(list);
    return  list.toArray(new Long[list.size()]);
    }

    /**
     * 当分类中的某些属性有改变时，与之关联的表也需要进行改变
     * @param category
     */
    @Override
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotEmpty(category.getName())){
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }
    }


    public List<Long> findParent(Long catelogId,List<Long> list) {
        CategoryEntity categoryEntity = this.getById(catelogId);
        list.add(catelogId);
        if (categoryEntity.getParentCid()!=0){
            this.findParent(categoryEntity.getParentCid(),list);
        }
        return list;
    }

    /**
     * 递归方法，查找所有菜单的子菜单
     * @param root:传进来的根菜单
     * @param all: 所有菜单的list集合
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> childrenList = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        })
                .map(categoryEntity -> {
                    //找到子菜单，递归找法
                    categoryEntity.setChildren(getChildren(categoryEntity,all));
                    return categoryEntity;
                })
                .sorted((menu1,menu2)->{
                    //找到以后进行排序
                    return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?1:menu2.getSort());
                })
                .collect(Collectors.toList());
        return childrenList;
    }
}
